<template>
  <div class="products-main-settings">
    <div class="page-header">
      <h1>产品页面配置</h1>
      <el-button type="primary" @click="initSettings" :loading="loading">
        <el-icon><RefreshRight /></el-icon>
        初始化默认配置
      </el-button>
    </div>

    <el-card>
      <!-- 基础配置表单 -->
      <MultiLangForm
        v-model="settings"
        :fields="['title', 'subtitle', 'description']"
        :placeholders="placeholders"
      />

      <!-- 头部背景图上传 -->
      <el-form-item label="页面头部背景图" class="image-upload-item">
        <div class="image-upload-container">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            accept="image/*"
          >
            <div v-if="headerImage" class="image-preview">
              <img :src="headerImage" alt="Header Background" />
              <div class="image-overlay">
                <el-icon><Camera /></el-icon>
                <span>点击更换</span>
              </div>
            </div>
            <div v-else class="image-placeholder">
              <el-icon class="image-placeholder-icon"><Camera /></el-icon>
              <div class="image-placeholder-text">点击上传头部背景图</div>
            </div>
          </el-upload>
          <div class="image-tips">
            <p>建议尺寸：1920x600像素</p>
            <p>支持 JPG、PNG 格式，文件大小不超过 5MB</p>
          </div>
        </div>
      </el-form-item>
    </el-card>

    <!-- 底部保存按钮 -->
    <div class="footer-actions">
      <el-button type="primary" @click="saveSettings" :loading="saving">
        <el-icon><Check /></el-icon>
        保存配置
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { request } from '../../../utils/request'
import { RefreshRight, Check, Camera } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps } from 'element-plus'
import MultiLangForm from '../../about/components/MultiLangForm.vue'

const loading = ref(false)
const saving = ref(false)

// 基础设置数据
const settings = reactive<Record<string, any>>({})

// 头部背景图
const headerImage = ref<string>('')

// 占位符配置
const placeholders = {
  title: {
    en: 'Enter English page title, e.g.: Our Products',
    es: 'Ingrese el título de la página en español',
    ja: '日本語のページタイトルを入力してください'
  },
  subtitle: {
    en: 'Enter English page subtitle',
    es: 'Ingrese el subtítulo de la página en español',
    ja: '日本語のページサブタイトルを入力してください'
  },
  description: {
    en: 'Enter English page description',
    es: 'Ingrese la descripción de la página en español',
    ja: '日本語のページ説明を入力してください'
  }
}

// 上传配置
const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/settings/upload/image`)
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('admin_token')
  return {
    'Authorization': `Bearer ${token}`
  }
})

// 获取设置数据
const getSettings = async () => {
  loading.value = true
  try {
    const response = await request.get('/settings') as any
    if (response.success) {
      // 清空现有数据
      Object.keys(settings).forEach(key => {
        delete settings[key]
      })
      headerImage.value = ''
      
      // 处理返回的数据
      response.data.forEach((item: any) => {
        if (item.key === 'products_header_image') {
          headerImage.value = item.value
        } else if (item.key.startsWith('products_page_')) {
          // 映射字段名
          const mappedKey = mapSettingKey(item.key)
          settings[mappedKey] = item.value
        }
      })
    }
  } catch (error) {
    console.error('获取配置失败:', error)
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

// 映射设置字段名
const mapSettingKey = (key: string): string => {
  const mapping: Record<string, string> = {
    'products_page_title_en': 'title_en',
    'products_page_title_es': 'title_es', 
    'products_page_title_ja': 'title_ja',
    'products_page_subtitle_en': 'subtitle_en',
    'products_page_subtitle_es': 'subtitle_es',
    'products_page_subtitle_ja': 'subtitle_ja',
    'products_page_description_en': 'description_en',
    'products_page_description_es': 'description_es',
    'products_page_description_ja': 'description_ja'
  }
  return mapping[key] || key
}

// 反向映射设置字段名
const reverseMapSettingKey = (key: string): string => {
  const mapping: Record<string, string> = {
    'title_en': 'products_page_title_en',
    'title_es': 'products_page_title_es',
    'title_ja': 'products_page_title_ja',
    'subtitle_en': 'products_page_subtitle_en',
    'subtitle_es': 'products_page_subtitle_es',
    'subtitle_ja': 'products_page_subtitle_ja',
    'description_en': 'products_page_description_en',
    'description_es': 'products_page_description_es',
    'description_ja': 'products_page_description_ja'
  }
  return mapping[key] || key
}

// 初始化默认设置
const initSettings = async () => {
  try {
    await ElMessageBox.confirm(
      '初始化将创建默认配置，已有配置不会被覆盖。是否继续？',
      '确认初始化',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const response = await request.post('/settings/init-products') as any
    if (response.success) {
      ElMessage.success('初始化成功')
      getSettings()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('初始化失败')
    }
  } finally {
    loading.value = false
  }
}

// 图片上传成功
const handleImageSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.success) {
    headerImage.value = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 图片上传前检查
const beforeImageUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 保存设置
const saveSettings = async () => {
  saving.value = true
  try {
    // 准备要保存的数据
    const settingsToSave: Record<string, any> = {}
    
    // 映射基础设置
    Object.keys(settings).forEach(key => {
      const mappedKey = reverseMapSettingKey(key)
      settingsToSave[mappedKey] = settings[key]
    })
    
    // 添加头部背景图
    settingsToSave['products_header_image'] = headerImage.value

    const response = await request.post('/settings/batch', {
      settings: settingsToSave
    }) as any

    if (response.success) {
      ElMessage.success('保存成功')
      await getSettings()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  getSettings()
})
</script>

<style scoped>
.products-main-settings {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.image-upload-item {
  margin-top: 20px;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.image-uploader {
  display: inline-block;
}

.image-preview {
  position: relative;
  width: 400px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.image-placeholder {
  width: 400px;
  height: 120px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.image-placeholder:hover {
  border-color: #409eff;
}

.image-placeholder-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.image-placeholder-text {
  color: #8c939d;
  font-size: 14px;
}

.image-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}

.image-tips p {
  margin: 2px 0;
}

.footer-actions {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
  text-align: center;
}
</style>